package com.playplus.wolat.cartoonvideo;

import java.io.File;
import java.util.Arrays;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

import com.facebook.*;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;

public class MainActivity extends Activity implements CvCameraViewListener{
    public static final int VIEW_MODE_NORMAL = 0;
    public static final int VIEW_MODE_CANNY = 1;
    public static final int VIEW_MODE_SOBEL = 2;
    public static final int VIEW_MODE_LAPLACIAN = 3;
    public static final int VIEW_MODE_SCHARR = 4;

    private static int viewMode = VIEW_MODE_CANNY;
    private MenuItem mItemPreviewNORMAL;
    private MenuItem mItemPreviewCanny;
    private MenuItem mItemPreviewSobel;
    private MenuItem mItemPreviewLaplacian;
    private MenuItem mItemPreviewScharr;
    private Mat mRgba;
    private Mat m8UC4;

    private CameraBridgeViewBase mOpenCvCameraView;
    
    private static boolean mPendingPublish = false;
    
    private ProgressDialog mProgressDialog = null;
    
    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) 
    {
        @Override
        public void onManagerConnected(int status) 
        {
            switch (status) 
            {
                case LoaderCallbackInterface.SUCCESS:
                {
                    mOpenCvCameraView.enableView();
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };
    
    private Session.StatusCallback callback = new Session.StatusCallback()
    {
    	@Override
    	public void call(Session session, SessionState state, Exception exception)
    	{
    		onSessionStateChange(session, state, exception);
    	}
    };
    
    private void onSessionStateChange(Session session, SessionState state, Exception exception)
    {
    	Log.v("cartoon video", session.toString());
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_main);
        
    	mProgressDialog = new ProgressDialog(this);
    	mProgressDialog.setTitle("Cartoon Video to Facebook");
    	mProgressDialog.setMessage("업로딩중입니다...");
    	mProgressDialog.setIndeterminate(true);

    	Session session = Session.getActiveSession();
        if (session == null || session.getState().isClosed())
        {
        	mPendingPublish = true;
        	session = Session.openActiveSession(this, true, callback);
        }
        
        mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.main_view);
        mOpenCvCameraView.setCvCameraViewListener(this);
        mOpenCvCameraView.setOnClickListener(new View.OnClickListener() 
        {
			@Override
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				
				postPhoto();
			}
		});
    }
    
    private synchronized void postPhoto()
    {
    	String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state))
        {
        	File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "cartoonvideo");
        	if (!file.isDirectory()) file.mkdirs();
        	
        	String path = file.getPath() + "/cv.jpg";
        	Highgui.imwrite(path, m8UC4);
        	
        	Session session = Session.getActiveSession();
    	
        	Log.v("cartoon video", "postPhoto()");

        	if (session != null)
        	{
        		Log.v("cartoon video", "postPhoto() - session");
        		Bitmap bitmap = BitmapFactory.decodeFile(path);

        		mOpenCvCameraView.setVisibility(View.INVISIBLE);
            	mProgressDialog.show();
            	
        		Request request = Request.newUploadPhotoRequest(session, bitmap, new Request.Callback() 
        		{
        			@Override
        			public void onCompleted(Response response) 
        			{
        				Log.v("cartoon video", "uploading the photo completed...");
        		        
        		        mProgressDialog.hide();
        		    	mOpenCvCameraView.setVisibility(View.VISIBLE);
        			}
        		});
        		request.executeAsync();
        	}
    	}
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    	super.onActivityResult(requestCode, resultCode, data);
    	Session session = Session.getActiveSession();
    	session.onActivityResult(this, requestCode, resultCode, data);
    	
    	if (mPendingPublish && session.isOpened())
    	{
    		mPendingPublish = false;
			session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, Arrays.asList("publish_actions")));
    	}
    }

    @Override
    public void onPause()
    {
    	if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
        super.onPause();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
    	
        Session session = Session.getActiveSession();
    	if (session != null && (session.isOpened() || session.isClosed()))
    	{
    		onSessionStateChange(session, session.getState(), null);
    	}
    }

    public void onDestroy() 
    {
        super.onDestroy();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }
    
    public void onCameraViewStarted(int width, int height) 
    {
        mRgba = new Mat(height, width, CvType.CV_8UC4);
        m8UC4 = new Mat(height, width, CvType.CV_8UC4);
    }

    public void onCameraViewStopped() 
    {
        mRgba.release();
        m8UC4.release();
    }

    public Mat onCameraFrame(Mat inputFrame) 
    {
        switch (viewMode) 
        {
            case VIEW_MODE_NORMAL:
                inputFrame.copyTo(mRgba);
                mRgba.copyTo(m8UC4);
                break;
            case VIEW_MODE_CANNY:
                Imgproc.Canny(inputFrame, mRgba, 40, 60);
                Core.bitwise_not(mRgba, mRgba);
                mRgba.copyTo(m8UC4);
            	break;
            case VIEW_MODE_SOBEL:
                Imgproc.Sobel(inputFrame, mRgba, -1, 1, 0);
                Core.bitwise_not(mRgba, mRgba);
                mRgba.copyTo(m8UC4);
        		break;
            case VIEW_MODE_LAPLACIAN:
                Imgproc.Laplacian(inputFrame, mRgba, 0, 5, 1, 1, Imgproc.BORDER_REFLECT);
                Core.bitwise_not(mRgba, mRgba);
                mRgba.copyTo(m8UC4);
        		break;
            case VIEW_MODE_SCHARR:
                Imgproc.Scharr(inputFrame, mRgba, 0, 0, 1);
                Core.bitwise_not(mRgba, mRgba);
                mRgba.copyTo(m8UC4);
        		break;
        }

        return mRgba;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        mItemPreviewNORMAL = menu.add("Normal");
        mItemPreviewCanny = menu.add("Canny");
        mItemPreviewSobel = menu.add("Sobel");
        mItemPreviewLaplacian = menu.add("Laplacian");
        mItemPreviewScharr = menu.add("Scharr");
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        if (item == mItemPreviewNORMAL)
        {
            mOpenCvCameraView.SetCaptureFormat(Highgui.CV_CAP_ANDROID_COLOR_FRAME_RGBA);
            viewMode = VIEW_MODE_NORMAL;
        }
        else if (item == mItemPreviewCanny)
        {
            mOpenCvCameraView.SetCaptureFormat(Highgui.CV_CAP_ANDROID_GREY_FRAME);
            viewMode = VIEW_MODE_CANNY;
        }
        else if (item == mItemPreviewSobel)
        {
            mOpenCvCameraView.SetCaptureFormat(Highgui.CV_CAP_ANDROID_GREY_FRAME);
            viewMode = VIEW_MODE_SOBEL;
        }
        else if (item == mItemPreviewLaplacian)
        {
            mOpenCvCameraView.SetCaptureFormat(Highgui.CV_CAP_ANDROID_GREY_FRAME);
            viewMode = VIEW_MODE_LAPLACIAN;
        }
        else if (item == mItemPreviewScharr)
        {
            mOpenCvCameraView.SetCaptureFormat(Highgui.CV_CAP_ANDROID_GREY_FRAME);
            viewMode = VIEW_MODE_SCHARR;
        }

        return true;
    }
}
